package cn.itcast.shop.user.action;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cn.itcast.shop.user.domain.User;
import cn.itcast.shop.user.exception.UserException;
import cn.itcast.shop.user.service.UserService;

/**
 * 用户模块Action
 */
public class UserAction extends ActionSupport implements ModelDriven<User> {
	private static final long serialVersionUID = 1L;

	/**
	 * 自动注入用户业务层对象
	 */
	@Autowired
	private UserService userService;

	/**
	 * 创建模型驱动对象
	 */
	private User user = new User();

	@Override
	public User getModel() {
		return user;
	}

	/**
	 * 返回注册页面
	 */
	public String registPage() {
		return "registPage";
	}

	/**
	 * 返回登录页面
	 */
	public String loginPage() {
		return "loginPage";
	}

	/**
	 * 注册功能
	 */
	public String regist() {
		//调用业务层的注册方法
		userService.regist(user);
		//获得Request对象
		HttpServletRequest req = ServletActionContext.getRequest();
		//根据用户邮箱后缀组装邮箱链接
		String mailAddres = "mail." + user.getEmail().substring(user.getEmail().indexOf("@") + 1);
		//向request域中存值
		req.setAttribute("mailAddress", mailAddres);
		req.setAttribute("code", "success");
		req.setAttribute("msg", "注册成功，请马上到邮箱激活");
		return "msg";
	}

	/**
	 * 登录功能
	 * 
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public String login() throws UnsupportedEncodingException {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		//调用业务层的登录方法查询用户信息
		user = userService.login(user);
		if (user != null) { 
			if (user.getState() == 1) { // 已经激活
				user.setPassword("");
				request.getSession().setAttribute("sessionUser", user); // 向session中保存user
				String isRememberUsername = request.getParameter("isRememberUsername");
				if(isRememberUsername!=null){//用户勾选了记住用户名
					String username = user.getUsername();
					username = URLEncoder.encode(username, "utf-8");// 设置编码
					Cookie cookie = new Cookie("username", username);//创建一个Cookie
					cookie.setMaxAge(60 * 60 * 48); // cookie 保存48小时
					response.addCookie(cookie);//将cookie传给浏览器
				}else{
					Cookie cookie = new Cookie("username", "");
					//清除客户端中的cookie
					cookie.setMaxAge(0);
					response.addCookie(cookie);
				}
				return "index";//跳转到主页
			} else { // 用户没有激活
				addFieldError("username", "你还没有激活！");//向页面添加错误信息
				return "loginPage";//跳转到登录页面
			}
		} else {// 用户不存在
			addFieldError("username", "用户名或密码错误！");//向页面添加错误信息
			return "loginPage";//跳转到登录页面
		}
	}
	/**
	 * 用户退出
	 * @return
	 */
	public String exit(){
		ServletActionContext.getRequest().getSession().invalidate();//销毁session
		return "index";//跳转到主页
	}

	/**
	 * 邮件激活
	 */
	public String activation() {
		HttpServletRequest req = ServletActionContext.getRequest();
		
		//获得激活码
		String activationCode = req.getParameter("activationCode");
		
		try {
			userService.activation(activationCode);//调用业务层的激活方法
		} catch (UserException e) {
			req.setAttribute("code", "error");//添加激活状态
			req.setAttribute("msg", e.getMessage());//添加激活信息
			return "msg";//跳转到信息页面
		}
		req.setAttribute("code", "success");//添加激活状态
		req.setAttribute("msg", "激活成功!");//添加激活信息
		return "msg";//跳转到信息页面
	}

	/**
	 * 注册表单校验方法
	 * 每次访问regist方法之前，Struct2框架会自动调用此方法
	 */
	public void validateRegist() {

		String username = user.getUsername();
		if (username == null || username.trim().isEmpty()) {
			addFieldError("username", "用户名不能为空！");
		} else if (!username.matches("\\w{3,10}$")) {
			addFieldError("username", "用户名只能是3~10位数字和字母的组合！");
		} else if (userService.findByUsername(username) != null) {
			addFieldError("username", "用户名已经被注册！");
		}

		// 密码校验
		String password = user.getPassword();
		if (password == null || password.trim().isEmpty()) {
			addFieldError("password", "密码不能为空！");
		} else if (!password.matches("\\w{6,16}$")) {
			addFieldError("password", "密码长度必须在6-16之间！");
		}

		// 确认密码校验
		String repassword = user.getRepassword();
		if (repassword == null || repassword.trim().isEmpty()) {
			addFieldError("repassword", "确认密码不能为空！");
		} else if (!repassword.equals(password)) {
			addFieldError("repassword", "两次密码不一致！");
		}

		// email校验
		String email = user.getEmail();
		if (email == null || email.trim().isEmpty()) {
			addFieldError("email", "邮箱不能为空！");
		} else if (!email.matches("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\\.[a-zA-Z0-9_-]{2,3}){1,2})$")) {
			addFieldError("email", "邮箱格式错误！");
		} else if (userService.findByEmail(email) != null) {
			addFieldError("email", "邮箱已经被注册！");
		}

		// 验证码校验
		String verifyCode = user.getVerifyCode();
		String vCode = (String) ServletActionContext.getRequest().getSession().getAttribute("vCode");
		if (verifyCode == null || verifyCode.trim().isEmpty()) {
			addFieldError("verifyCode", "验证码不能为空！");
		} else if (!verifyCode.equalsIgnoreCase(vCode)) {
			addFieldError("verifyCode", "验证码错误！");
		}
	}

	/**
	 * 登录表单校验
	 * 每次访问login方法之前，Struct2框架会自动调用此方法
	 */
	public void validateLogin() {

		String username = user.getUsername();
		if (username == null || username.trim().isEmpty()) {
			addFieldError("username", "用户名不能为空！");
		} else if (!username.matches("\\w{3,10}$")) {
			addFieldError("username", "用户名格式错误！");
		}
		// 密码校验
		String password = user.getPassword();
		if (password == null || password.trim().isEmpty()) {
			addFieldError("password", "密码不能为空！");
		} else if (!password.matches("\\w{6,16}$")) {
			addFieldError("username", "用户名或密码错误！");
		}
		// 验证码校验
		String verifyCode = user.getVerifyCode();
		String vCode = (String) ServletActionContext.getRequest().getSession().getAttribute("vCode");
		if (verifyCode == null || verifyCode.trim().isEmpty()) {
			addFieldError("verifyCode", "验证码不能为空！");
		} else if (!verifyCode.equalsIgnoreCase(vCode)) {
			addFieldError("verifyCode", "验证码错误！");
		}
	}

	/**
	 * AJAX异步校验用户名
	 * 
	 * @return
	 * @throws IOException
	 */
	public String findByUsername() throws IOException {
		//通过用户名去数据库查找
		User existUser = userService.findByUsername(user.getUsername());
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html;charset=UTF-8");
		if (existUser != null) {//此用户名已经存在
			response.getWriter().println("true");
		} else {//此用户名不存在
			response.getWriter().println("false");
		}
		return NONE;
	}

	/**
	 * AJAX异步校验邮箱
	 * 
	 * @return
	 * @throws IOException
	 */
	public String findByEmail() throws IOException {
		//通过邮箱名去数据库查询
		User existUser = userService.findByEmail(user.getEmail());
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html;charset=UTF-8");
		if (existUser != null) {
			response.getWriter().println("true");
		} else {
			response.getWriter().println("false");
		}
		return NONE;
	}
}
